import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../API/user/user.dart';

class ForgetPasswordController extends GetxController {
  // 状态管理变量
  RxBool showPassword1 = false.obs;
  RxBool showPassword2 = false.obs;
  RxString phone = ''.obs;
  RxString password1 = ''.obs;
  RxString password2 = ''.obs;
  RxString code = ''.obs;
  RxInt countdown = 0.obs;
  RxBool isCodeSent = false.obs;

  late Timer timer;

  // 发送验证码
  Future<bool> sendCode(String phone) async {
    if (phone.length != 11) {
      Get.snackbar("错误", "手机号必须为11位数字");
      return false;
    }

    final response = await ApiService.sendCode(phone);
    final int code = response["code"];

    if (code == 40011) {
      Get.snackbar("成功", "验证码已发送", snackPosition: SnackPosition.TOP);
      return true;
    } else {
      Get.snackbar(
        "错误",
        response['message'] ?? "发送失败",
        duration: const Duration(seconds: 5),
        snackPosition: SnackPosition.TOP,
      );
      return false;
    }
  }

  // 开始倒计时
  void startCountdown() {
    countdown.value = 60;
    isCodeSent.value = true;

    timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (countdown.value == 0) {
        timer.cancel();
        isCodeSent.value = false;
      } else {
        countdown.value--;
      }
    });
  }

  // 注册逻辑
  Future<void> forgetPassword() async {
    if (validateForm()) {
      final response = await ApiService.forgetPassword(
        phone: phone.value,
        password: password1.value,
        code: code.value,
      );

      if (response["code"] == 20031) {
        Get.back();
        Get.snackbar("成功", "修改密码成功", snackPosition: SnackPosition.TOP);
      } else {
        Get.snackbar(
          "错误",
          "修改密码失败: ${response['message']}",
          duration: const Duration(seconds: 5),
        );
      }
    }
  }

  // 表单验证
  bool validateForm() {
    if (phone.value.isEmpty || phone.value.length != 11) {
      Get.snackbar("错误", "请输入正确的手机号");
      return false;
    }
    if (password1.value.isEmpty || password1.value.length < 6) {
      Get.snackbar("错误", "密码最少六个字符");
      return false;
    }
    if (password2.value.isEmpty || password2.value != password1.value) {
      Get.snackbar("错误", "两次密码不一致");
      return false;
    }
    if (code.value.isEmpty || code.value.length != 4) {
      Get.snackbar("错误", "验证码必须为4位");
      return false;
    }
    return true;
  }

  // 清除定时器
  @override
  void onClose() {
    timer.cancel();
    super.onClose();
  }
}

class ForgetPasswordPage extends StatelessWidget {
  const ForgetPasswordPage({super.key});

  @override
  Widget build(BuildContext context) {
    final ForgetPasswordController controller = Get.put(
      ForgetPasswordController(),
    );
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Color(0xFF0088FF),
        title: const Text("修改密码", style: TextStyle(color: Colors.white)),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () {
            Get.back();
          },
        ),
      ),
      body: Container(
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [Color(0xFF0088FF), Colors.cyanAccent],
          ),
        ),
        child: ListView(
          padding: EdgeInsets.all(45),
          children: [
            _buildPhoneField(controller),
            const SizedBox(height: 40),
            _buildPasswordField(controller, isConfirm: false),
            const SizedBox(height: 40),
            _buildPasswordField(controller, isConfirm: true),
            const SizedBox(height: 40),
            _buildVerificationCodeSection(controller),
            const SizedBox(height: 40),
            ElevatedButton(
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.white,
                foregroundColor: Colors.blue,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(20),
                ),
                padding: const EdgeInsets.symmetric(horizontal: 80),
              ),
              onPressed: controller.forgetPassword,
              child: const Text('确认修改'),
            ),
          ],
        ),
      ),
    );
  }
}

Widget _buildPhoneField(ForgetPasswordController controller) {
  return TextFormField(
    decoration: const InputDecoration(
      labelText: '手机号',
      hintText: '请输入11位手机号',
      labelStyle: TextStyle(color: Colors.white),
      hintStyle: TextStyle(color: Colors.white),
      enabledBorder: UnderlineInputBorder(
        borderSide: BorderSide(color: Colors.white),
      ),
      focusedBorder: UnderlineInputBorder(
        borderSide: BorderSide(color: Colors.white),
      ),
    ),
    keyboardType: TextInputType.phone,
    style: const TextStyle(color: Colors.white),
    onChanged: (value) => controller.phone.value = value,
  );
}

Widget _buildPasswordField(
  ForgetPasswordController controller, {
  required bool isConfirm,
}) {
  return Obx(
    () => TextFormField(
      decoration: InputDecoration(
        labelText: isConfirm ? '确认密码' : '密码',
        hintText: isConfirm ? '请确认密码' : '请输入密码',
        labelStyle: const TextStyle(color: Colors.white),
        hintStyle: const TextStyle(color: Colors.white),
        suffixIcon: IconButton(
          icon: Icon(
            (isConfirm
                    ? controller.showPassword2.value
                    : controller.showPassword1.value)
                ? Icons.visibility_off
                : Icons.visibility,
            color: Colors.white,
          ),
          onPressed:
              (isConfirm
                  ? controller.showPassword2.toggle
                  : controller.showPassword1.toggle),
        ),
        enabledBorder: const UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.white),
        ),
        focusedBorder: const UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.white),
        ),
      ),
      style: const TextStyle(color: Colors.white),
      obscureText:
          isConfirm
              ? !controller.showPassword2.value
              : !controller.showPassword1.value,
      onChanged: (value) {
        if (isConfirm) {
          controller.password2.value = value;
        } else {
          controller.password1.value = value;
        }
      },
    ),
  );
}

Widget _buildVerificationCodeSection(ForgetPasswordController controller) {
  return Row(
    children: [
      Expanded(
        child: TextFormField(
          decoration: const InputDecoration(
            labelText: '验证码',
            labelStyle: TextStyle(color: Colors.white),
            hintStyle: TextStyle(color: Colors.white),
            enabledBorder: UnderlineInputBorder(
              borderSide: BorderSide(color: Colors.white),
            ),
            focusedBorder: UnderlineInputBorder(
              borderSide: BorderSide(color: Colors.white),
            ),
          ),
          style: const TextStyle(color: Colors.white),
          onChanged: (value) => controller.code.value = value,
        ),
      ),
      const SizedBox(width: 10),
      SizedBox(
        width: 120,
        child: Obx(()=>
            ElevatedButton(
              style: ElevatedButton.styleFrom(
                backgroundColor: controller.isCodeSent.value
                    ? Colors.grey
                    : (controller.phone.value.length == 11
                    ? Colors.blue
                    : Color(0xCD9E9E9E)),
              ),
              onPressed: () async {
                if (!controller.isCodeSent.value && controller.phone.value.length == 11) {
                  if (await controller.sendCode(controller.phone.value)) {
                    controller.startCountdown();
                  }
                } else {
                  Get.snackbar("错误", "请检查手机号格式");
                }
              },
              child: Text(
                controller.isCodeSent.value ? '${controller.countdown.value}秒后重发' : '获取验证码',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: controller.isCodeSent.value ? 12 : 14,
                ),
              ),
            ),
        ),
      ),
    ],
  );
}
